package com.miyake.dsp.osa.lab;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.thoughtworks.xstream.XStream;

public class PersistentManager {
	class OmitField {
		public Class getCls() {
			return cls;
		}
		public String getField() {
			return field;
		}
		public OmitField(Class cls, String field) {
			this.cls = cls;
			this.field = field;
		}
		private Class cls;
		private String field;
		
	};
	
	private static List<OmitField> omitFields = new ArrayList<OmitField>();
	private static PersistentManager instance;
	private PersistentManager() {
		
	}
	public static PersistentManager getInstance() {
		if (instance == null) {
			instance = new PersistentManager();
		}
		return instance;
	}
	
	public void addOmitField(Class cls, String field) {
		omitFields.add(new OmitField(cls, field));
	}
	
	public synchronized void save(String filename, List<List<LabContainer>> object) {
		
		for (List<LabContainer> list : object) {
			for (LabContainer c : list) {
				c.clear();
			}
		}
		
		if (!filename.endsWith(".xml")) {
			filename += ".xml";
		}
		XStream xstream = new XStream();
		xstream.omitField(LabContainer.class, "ui");
		xstream.omitField(Connector.class, "data");
//		xstream.omitField(Calculator.class, "inputMap");
//		xstream.omitField(Calculator.class, "outputMap");
		for (OmitField f : omitFields) {
			xstream.omitField(f.getCls(), f.getField());
		}
		//xstream.omitField(OtdrSetting.class, "entryPoint");
		String xml = xstream.toXML(object);
		try {
			BufferedWriter writer = new BufferedWriter(new FileWriter(new File(filename)));
			writer.write(xml);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public synchronized List<List<LabContainer>> open(String filename) {
		try {
			BufferedReader  reader = new BufferedReader (new FileReader(new File(filename)));
			XStream xstream = new XStream();
			String xml = "";
			String s;
			while((s = reader.readLine()) != null) {
				xml += s;
			}
			List<List<LabContainer>> obj = (List<List<LabContainer>>)xstream.fromXML(xml);
			reader.close();
			return obj;
		} catch (FileNotFoundException e) {
			//e.printStackTrace();
			System.out.println("Lauched with default setting");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
